﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Web.Mvc;
using System.Web.Security;
using Sharp.Platform.Mvc.Models;

namespace Sharp.Platform.Mvc.Filter
{
    //[DebuggerStepThrough]
    public class AuthorizeFilter : ActionFilterAttribute
    {
        //Action方法执行之前执行此方法       
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var allowAnonymous4Action =
                filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), false).Any();

            var allowAnonymous4Controller = filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), false).Any();
            if (allowAnonymous4Action || allowAnonymous4Controller)
            {
                return;
            }

            base.OnActionExecuting(filterContext);

            foreach (var item in filterContext.ActionParameters)
            {
                var model = item.Value as BaseViewModel;
                if (model != null)
                {
                    model.OP = filterContext.HttpContext.User.Identity.Name;
                }
            }
            //filterContext.HttpContext.User.Identity.IsAuthenticated
            //权限判断
            if (!filterContext.RequestContext.HttpContext.Request.IsAuthenticated)
            {
                FormsAuthentication.RedirectToLoginPage();
            }

        }
    }
}
